package com.hhh.springai_test.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhh.springai_test.common.ErrorCode;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.model.dto.readingRoom.AddReadingRoomRequest;
import com.hhh.springai_test.model.dto.readingRoom.UpdateReadingRoomRequest;
import com.hhh.springai_test.model.po.ReadingRoom;
import com.hhh.springai_test.service.ReadingRoomService;
import com.hhh.springai_test.mapper.ReadingRoomMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author 29915
* @description 针对表【reading_room(阅览室信息表)】的数据库操作Service实现
* @createDate 2025-02-04 11:06:13
*/
@Service
public class ReadingRoomServiceImpl extends ServiceImpl<ReadingRoomMapper, ReadingRoom>
    implements ReadingRoomService{

    @Override
    public long addReadingRoom(AddReadingRoomRequest addReadingRoomRequest) {
        if (addReadingRoomRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        QueryWrapper<ReadingRoom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roomname", addReadingRoomRequest.getRoomname());
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "阅览室名称重复");
        }
        Integer totalseats = addReadingRoomRequest.getTotalseats();
        if (totalseats == null || totalseats <= 0 || totalseats > 120) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位数量必须在1-120之间");
        }
        String openinghours = addReadingRoomRequest.getOpeninghours();
        if (openinghours == null || !openinghours.contains("|")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开放时间格式不正确，应包含'|'分隔符");
        }
        String timeStr = openinghours.split("\\|")[1].trim();
        if (!timeStr.matches("\\d{1,2}:\\d{2}-\\d{1,2}:\\d{2}")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "时间格式不正确，应为：HH:mm-HH:mm");
        }
        String[] parts = timeStr.split("-");
        String[] startTime = parts[0].trim().split(":");
        String[] endTime = parts[1].trim().split(":");
        
        int startHour = Integer.parseInt(startTime[0]);
        int startMinute = Integer.parseInt(startTime[1]);
        int endHour = Integer.parseInt(endTime[0]);
        int endMinute = Integer.parseInt(endTime[1]);
        
        if (startHour < 0 || startHour > 23 || endHour < 0 || endHour > 23 ||
            startMinute < 0 || startMinute > 59 || endMinute < 0 || endMinute > 59) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "时间格式必须是24小时制");
        }
        ReadingRoom readingRoom = new ReadingRoom();
        BeanUtils.copyProperties(addReadingRoomRequest, readingRoom);
        readingRoom.setCurrentcount(0);
        StringBuilder seatStatus = new StringBuilder("[");
        for (int i = 1; i <= totalseats; i++) {
            seatStatus.append("{\"id\":").append(i)
                     .append(",\"number\":").append(i)
                     .append(",\"status\":1}");
            if (i < totalseats) {
                seatStatus.append(",");
            }
        }
        seatStatus.append("]");
        readingRoom.setSeatstatus(seatStatus.toString());
        boolean result = this.save(readingRoom);
        if (!result) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "添加阅览室房间失败");
        }
        return readingRoom.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReadingRoom(UpdateReadingRoomRequest updateReadingRoomRequest) {
        if (updateReadingRoomRequest == null || updateReadingRoomRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = updateReadingRoomRequest.getId();
        if (this.getById(id) == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该阅览室不存在");
        }
        if(updateReadingRoomRequest.getTotalseats() <= 0 ||updateReadingRoomRequest.getTotalseats() >120){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位数量必须在1-120之间");
        }
        String seatstatus = updateReadingRoomRequest.getSeatstatus();
        Integer totalseats = updateReadingRoomRequest.getTotalseats();
        try {
            JSONArray seatArray = JSONArray.parseArray(seatstatus);
            if (seatArray.size() != updateReadingRoomRequest.getTotalseats()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位状态列表数量与总座位数不一致");
            }
            // 验证每个座位对象的格式
            for (int i = 0; i < seatArray.size(); i++) {
                JSONObject seat = seatArray.getJSONObject(i);
                if (!seat.containsKey("id") || !seat.containsKey("number") || !seat.containsKey("status")) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位状态格式不正确");
                }
                // 验证status值是否为0或1
                int status = seat.getIntValue("status");
                if (status != 0 && status != 1) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位状态值必须为0或1");
                }
                
                // 验证id和number的值是否在有效范围内且依次递增
                int ids = seat.getIntValue("id");
                int number = seat.getIntValue("number");
                if (ids <= 0 || ids > totalseats || number <= 0 || number > totalseats) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位ID或编号超出有效范围");
                }
                
                // 验证id和number是否等于当前索引+1(确保依次递增)
                if (ids != (i + 1) || number != (i + 1)) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位ID和编号必须从1开始依次递增");
                }
            }
        } catch (JSONException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位状态格式不正确");
        }
        String openinghours = updateReadingRoomRequest.getOpeninghours();
        if (openinghours == null || !openinghours.matches("周一至周日\\s*\\|\\s*\\d{1,2}:\\d{2}-\\d{1,2}:\\d{2}")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开放时间格式不正确，应为：周一至周日 |8:00-22:00");
        }
        String[] parts = openinghours.split("\\|")[1].trim().split("-");
        String[] startTime = parts[0].trim().split(":");
        String[] endTime = parts[1].trim().split(":");
        
        int startHour = Integer.parseInt(startTime[0]);
        int startMinute = Integer.parseInt(startTime[1]);
        int endHour = Integer.parseInt(endTime[0]);
        int endMinute = Integer.parseInt(endTime[1]);
        
        if (startHour < 0 || startHour > 23 || endHour < 0 || endHour > 23 ||
            startMinute < 0 || startMinute > 59 || endMinute < 0 || endMinute > 59) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "时间格式必须是24小时制");
        }

        ReadingRoom readingRoom = new ReadingRoom();
        BeanUtils.copyProperties(updateReadingRoomRequest, readingRoom);
        return this.updateById(readingRoom);
    }

    @Override
    public boolean deleteReadingRoom(Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (this.getById(id) == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该阅览室不存在");
        }
        return this.removeById(id);
    }

    @Override
    public ReadingRoom getReadingRoomById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ReadingRoom readingRoom = this.getById(id);
        if (readingRoom == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "阅览室不存在");
        }
        return readingRoom;
    }
}




